package com.vinjogames.som.entities;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.PointF;

import com.vinjogames.gfx.Camera;
import com.vinjogames.gfx.GUI;

public class Game {

	private Player p;
	private Map m;
	
	private GUI mGUI;
	private PointF touchLoc;
	private PointF dragLoc;
	
	private boolean isMoving;
	
	private int mode;
	
	public Game(){
		mGUI = new GUI();
		touchLoc = new PointF(0, 0);
		dragLoc = new PointF(0, 0);
		isMoving = false;
	}

	public void start() {
		p = new Player();
		m = new Map(0,0);
		
		m.initializeMap(Map.staticMap);
	}
	
	public void update(long t){
		mGUI.update();
		updateViewStuff();
		p.update(t);
	}
	
	private void updateViewStuff(){
		if(getPlayer() != null) {
			Camera.getInstance().setFocusedPlayer(getPlayer());
		}
	}

	public void draw(GL10 gl) {
		gl.glPushMatrix();
		Camera cam = Camera.getInstance();
		if(cam.getFocusedPlayer() != null){ cam.center(cam.getFocusedPlayer().getLocation()); }
		gl.glScalef(cam.getScale(), cam.getScale(), 1);

		gl.glTranslatef(-cam.getLeft()-Camera.GL_WIDTH/2, -cam.getBottom()-Camera.GL_HEIGHT/2,  Camera.Z_DISTANCE);
		m.draw(gl, p.getLocation());
		if(p.getMoveState() > 0){
			m.updateSurroundingTiles(p.getLocation(), -1);
		}
		p.draw(gl);
		
		gl.glPopMatrix();
		gl.glTranslatef(-Camera.GL_WIDTH/2, -Camera.GL_HEIGHT/2,  Camera.Z_DISTANCE);
		mGUI.draw(gl);
	}

	public GUI getGUI() { return mGUI; }
	
	public Player getPlayer() { return p; }
	public int getMode() { return mode; }
	
	public boolean isMoving() { return isMoving; }
	
	public void handleTouch(PointF loc){
		if(touchLoc.equals(0, 0));
			touchLoc.set(Camera.getInstance().getGLX(loc.x), Camera.getInstance().getGLY(loc.y));

		if(mGUI.handleTouch(touchLoc) && !isMoving){
			isMoving = true;
			p.setMoveState(mGUI.calculateTouchMove(mGUI.move(touchLoc)));
		}
	}
	
	public void handleDrag(PointF loc){
		
		if(isMoving){
			p.setMoveState(mGUI.calculateTouchMove(mGUI.handleMove(loc)));
		}
	}
	
	public void handleUp(PointF loc){
		if(isMoving){
			mGUI.handleUp(loc);
			isMoving = false;
			dragLoc.set(0,0);;
			touchLoc.set(0,0);
			p.setMoveState(0);
			// 0.5f since tiles are 1f.  Centers into the middle of the tile.
//			p.setLocation((float) Math.floor(p.getLocation().x) + 0.5f, (float) Math.floor(p.getLocation().y) + 0.5f);
			p.setLocation((p.getLocation().x), (p.getLocation().y));
		}
	}
}
